import sys;
sys.path.append('..');
from by.vaukalak.core.events.EventDispatcher import *;
from by.vaukalak.core.events.Event import *;
from by.vaukalak.core.application.Application import *;
from by.vaukalak.core.net.socket.SocketConnection import *;
from by.vaukalak.core.net.socket.SocketEvent import *;
import socket;
import time;

class SocketServer(EventDispatcher):

    def __init__(self, myHost, myPort):
        EventDispatcher.__init__(self);
        self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM);    # create a TCP socket
        self.s.bind((myHost, myPort));            # bind it to the server port
        self.s.listen(20);
        self.s.setblocking(0);
        self.connections = list();
        Application.enterFrameDispatcher.addEventListener("enterFrame", self.listenConnections)

    def updateConnectionsList(self):
        newConnection = None;
        try:
            newConnection, address = self.s.accept(); # connection is a new socket
        except:
            pass;
        if(newConnection):
            sc = SocketConnection(newConnection,address);
            sc.addEventListener(SocketEvent.CONNECTION_INTERRUPED, self.handleConnectionInterruped)
            self.connections.append(sc);
            self.dispatchEvent(SocketEvent(SocketEvent.NEW_CONNECTION, sc));

    def handleConnectionInterruped(self, event):
        self.connections.remove(event.target);

    def listenConnectionMessages(self):
        for conn in self.connections:
            data = conn.listen(1024); # receive up to 1K bytes

    def broadCastMessage(self, message):
        for tConn in self.connections:
            tConn.send('echo -> ' + message);

    def listenConnections(self, event):
        self.updateConnectionsList();
        self.listenConnectionMessages();